package com.example.yilanchatserver.application.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.yilanchatserver.business.freechat.*;
import com.example.yilanchatserver.business.freechat.service.FuJiaService;
import com.example.yilanchatserver.business.freechat.service.RedisService;
import com.example.yilanchatserver.business.freechat.service.ZhiPuService;
import com.example.yilanchatserver.business.freechat.service.dto.ChatInputDTO;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatDTO;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatInputDTO;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatPromptDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

@ServerEndpoint(value = "/bot/llm/chat/get/stream")
@Component
@Slf4j
public class FuJiaWebSocketServer {
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<FuJiaWebSocketServer> webSocketSet = new CopyOnWriteArraySet<FuJiaWebSocketServer>();

    private final HashMap<Session, String> contentMap = new HashMap<>();


    private static FuJiaService fuJiaService;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    //    public ChatGPTWebSocketServer_metah(){
//        this.chatGPTService = SpringUtil.getBean(ChatGPTService.class);
//    }
    @Resource
    private void setChatGPTService(FuJiaService fuJiaService){
        FuJiaWebSocketServer.fuJiaService = fuJiaService;

    }






    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        contentMap.put(session, "");
        addOnlineCount(); //在线数加1

//        String img1 = "img1";
//        String img2 = "img2";

        int cnt = 0;
//        try {
//            sendMessage("连接成功");
//            System.out.println("连接成功");
//        } catch (IOException e) {
//
//        }
    }

    /**
     * 图片转base64字符串
     *
     * @param imgFile 图片路径
     * @return
     */
    public static String imageToBase64Str(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
        subOnlineCount(); //在线数减1

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param inputQuestion 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String inputQuestion, Session session) throws Exception {


        for (FuJiaWebSocketServer item : webSocketSet) {
            if(item.session!=session){
                continue;
            }

            ChatInputDTO freeChatDTO = JSON.parseObject(inputQuestion, ChatInputDTO.class);
            Flux<String> response = fuJiaService.send(freeChatDTO.getTalkList().get(0).get("text"));

            response.publishOn(Schedulers.parallel()).subscribe(message -> {
//            response.subscribe(message -> {
                try {

                    if(!"[Done]".equals(message) && !"[Error]".equals(message)){
                        String noHtmlContent = message.replaceAll("<[^>]*>|\\n|\\*\\*", "");
//                        item.sendMessage(BaseResponseEntity.SUCCESS(noHtmlContent));
//
                        String appContent;
                        String content = contentMap.get(session);
                        if (StringUtils.isNotBlank(content)) {
                            if (noHtmlContent.contains(content)) {
                                appContent = noHtmlContent.replaceAll(content, "");
                                contentMap.put(session, noHtmlContent);
                            } else {
                                appContent = "";
                                contentMap.put(session, noHtmlContent);
                            }
                        } else {
                            appContent = noHtmlContent;
                            contentMap.put(session, noHtmlContent);
                        }
                        item.sendMessage(BaseResponseEntity.SUCCESS(appContent));

//                        TimeUnit.MILLISECONDS.sleep(20);
                    }
                    else if("[Done]".equals(message)){
                        item.sendMessage(BaseResponseEntity.FINISH());
                        item.closeSession();
                        contentMap.remove(session);
                    }
                    else{
                        item.sendMessage(BaseResponseEntity.ERROR());
                        item.closeSession();
                        contentMap.remove(session);
                    }
                } catch (Exception e) {
                    try {
                        item.closeSession();
                        contentMap.remove(session);
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            });

        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    public void closeSession() throws IOException {
        this.session.close();
    }

    public void sendMessage(BaseResponseEntity baseResponseEntity) throws IOException {
        String message = JSON.toJSONString(baseResponseEntity);
        if(this.session.isOpen()){
            this.session.getBasicRemote().sendText(message);
        }
        else{
            webSocketSet.remove(this);
        }

    }


    /**
     * 群发自定义消息
     * */
//    public static void sendInfo(String message) throws IOException {
//
//        for (CharacterChatWebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(message);
//            } catch (IOException e) {
//                continue;
//            }
//        }
//    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        FuJiaWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        FuJiaWebSocketServer.onlineCount--;
    }
}
